// ==UserScript==
// @name           TDWTFMT
// @namespace      https://code.google.com/p/tdwtfmt/
// @description    TDWTF Moderator tools
// @include        http://forums.thedailywtf.com/*

// @copyright      2010 P.J.Herring
// @version        $Revision: 10 $
// @date           $Date: 2013-05-31 11:42:36 +0000 (Fri, 31 May 2013) $
// ==/UserScript==

var deletereason_name='ctl00$ctl00$bcr$bcr$ctl02$ctl03$DeleteReason';
var deletebutton_name='ctl00$ctl00$bcr$bcr$ctl02$ctl03$DeletePost';

var accountstatus_name='ctl00$ctl00$OuterTaskRegion$TaskRegion$accountStatus';
var savechanges_name = 'ctl00_ctl00_OuterTaskRegion_TaskRegion_updateButton';

var postdiv_name="ForumPostArea";
var max_history=50;

/* ===== Click on an element (borrowed from Facebook Fixer, @namespace http://userscripts.org/people/14536) ===== */
function click(elm) {
     var evt = document.createEvent('MouseEvents');
     evt.initMouseEvent('click', true, true, window, 0, 1, 1, 1, 1, false, false, false, false, 0, null);
     elm.dispatchEvent(evt);

} 

/** @brief Change "Pending" to "Disapproved" on the accounts pending screen
 */
function changeAccountStatus(){
	var selects = document.getElementsByTagName('select');
	var pending = false;
	var savechanges;
	if (document.location.href.indexOf("membership/UserEdit.aspx?UserID=") <= 0)
		return;

	for (i=0; i<selects.length; i++){
		if (selects[i].name == accountstatus_name){
			GM_log(selects[i].value);
			for( v=0; v< selects[i].options.length; ++v){
				if (selects[i].options[v].value == 0){ // Pending approval
					pending = selects[i].options[v].selected;
// 					GM_log("pending = "+pending);
				}
			}
			if (pending){
				for( v=0; v< selects[i].options.length; ++v){
					if (selects[i].options[v].value == 3){ // Disapproved
						selects[i].options[v].selected = true;
						GM_log("Disapproved selected");
					}else{
						selects[i].options[v].selected = false;
					}
				}
				document.getElementById(savechanges_name).click();
			}
		}
	}
}

/** @brief can you believe that JS doesn't have it's own padleft function yet?
 */
Number.prototype.padLeft = function(width, char) {
	if (!char)
		char = " ";
	if (("" + this).length >= width)
		return "" + this;
	else
		return new Array(width-(""+this).length+1).join(char)+this;
};

/** @brief Automatically fill out the "Reason" box and submit the deletion form
 * Will only do it once per message (if seen in the past 50 deletions) - will turn background
 * green if seen before
 */
function autoDelete(){
	var postId = 0;
	if (GM_getValue("autodelete", "0") == 0) // disabled
		return;
	if (document.location.href.indexOf("DeletePost.aspx?PostID=") <= 0) // not a delete post page
		return;
	if (!/PostID=(\d+)/.test(document.location.href)) // no PostID found
		return; // no post ID
	postId = RegExp.$1;

	for(hist = 0; hist< max_history; hist = hist+1){
		if (postId == GM_getValue("delete/"+hist.padLeft(3,"0"), "") ) {
			addGlobalStyle('body { background-color:green; }'); // mark as green to indicate nothing will be done automatically
			document.title = 'X-Already seen/deleted-'+document.title;
			return;
		}
	}	

	var histcount=parseInt(GM_getValue("delete/count", "0"));
	GM_setValue("delete/"+histcount.padLeft(3,"0"), postId);
	GM_setValue("delete/count", (parseInt(histcount)+1) % max_history);
	
	var divs = document.getElementsByTagName('div');
	for (i=0; i<divs.length; i++){
		if (divs[i].className == postdiv_name){
			var postdiv = divs[i];
		}
	}
	if (postdiv == undefined){
		GM_log("Couldn't find postdiv");
	}else{
		GM_log("Found postdiv");
		if (parseInt(GM_getValue("showposts", 1)) == 0){
			postdiv.parentNode.removeChild(postdiv);
		}
	}
	
	var textareas = document.getElementsByTagName('textarea');
	for (i=0; i<textareas.length; i++){
		if (textareas[i].name == deletereason_name){
			var deletereason = textareas[i];
		}
	}
	
	if (deletereason == undefined){
		GM_log("Couldn't find delete reason textarea");
		return;
	}
	
	deletereason.value="X-TDWTFMT: Spam ($Revision: 10 $)";
	
	var buttons = document.getElementsByTagName('input');
	for (i=0; i<buttons.length; i++){
		if (buttons[i].name == deletebutton_name){
			var deletebutton = buttons[i];
		}
	}
	
	if (deletebutton == undefined){
		GM_log("Couldn't find delete button");
		return;
	}
	
	var deleteButton2;
	deletebutton2 = document.createElement('button');
	deletebutton2.type="submit";
	deletebutton2.name=deletebutton_name;
	deletebutton2.value="Delete Post";
	deletebutton2.onclick="return confirm('Are you sure you want to delete this post?');WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ctl00$bcr$bcr$ctl02$ctl03$DeletePost&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))";
	deletebutton2.id="ctl00_ctl00_bcr_bcr_ctl02_ctl03_DeletePost";
	deletebutton2.width=100;
	deletebutton2.height=50;
	
	deletebutton.parentNode.insertBefore(deletebutton2, deletebutton);
	click(deletebutton2);
}

/** @brief add CSS styling to the whole document
 */
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

/** @brief turn the background red if the current page appears to be a post in the deleted items folder
 */
function detectDeleted(){
	isDeleted = undefined;
	
	var anchors = document.getElementsByTagName('a');
	for (i=0; i<anchors.length; i++){
		if (anchors[i].href == 'http://forums.thedailywtf.com/forums/2.aspx'){
			addGlobalStyle('body { background-color:red; }');
			document.title = 'X-'+document.title;
			return;
		}
	}
}

/** @brief Modify user links to point to control panel editor.
 * In the deleted items folder list, the username link is changed
 * In the member search page the 'Priave Message' button/link is changed
 * 
 * Original idea and code from dhromed
 */
function userLinks(){
	/*
	 *  This script modifies links on some pages containing "UserID" to link to the user-edit page
	 * 
	 * Initial code/idea by dhromed
	 */
	
	var userLinks = document.getElementsByTagName('A');
	var reProfileLink = /UserID=(\d+)$/i;
	var reProfileEntireLink = /^.+=(\d+)$/;
	var urlEditProfile = 'http://forums.thedailywtf.com/controlpanel/membership/UserEdit.aspx?UserID=';
	
	// which URLs to match
	var includesRegex = [/^http:\/\/forums.thedailywtf.com\/forums\/2.aspx$/,
						   /^http:\/\/forums.thedailywtf.com\/user\/Members.aspx/
						   ];
	var matchUrl=0;
	for( var i=0; i < includesRegex.length; ++i){
		if (includesRegex[i].test(document.URL)){
			matchUrl =1;
			break;
		}
	}
	if (!matchUrl)
		return;
	
	for (var i=0; i < userLinks.length; i++) {
		var _link = userLinks[i];
		if (reProfileLink.test(_link.href)) {
			_link.href = _link.href.replace(reProfileEntireLink, urlEditProfile + RegExp.$1);
			if (_link.innerHTML == "Private Message")
				_link.innerHTML = "Edit User";
		}
	}
}



/** Add menus to the GM commands submenu
 */
if (GM_getValue("autodelete", "0") == 0)
	GM_registerMenuCommand("Enable Autodeletion", function(){GM_setValue("autodelete", 1); document.location.reload();})
else
	GM_registerMenuCommand("Disable Autodeletion", function(){GM_setValue("autodelete", 0); document.location.reload();})

if (GM_getValue("showposts", 1) == 1)
	GM_registerMenuCommand("Hide posts", function(){GM_setValue("showposts", 0); document.location.reload();})
else
	GM_registerMenuCommand("Show posts", function(){GM_setValue("showposts", 1); document.location.reload();})


GM_log("Started wtf");
detectDeleted(); // change background and title on already deleted posts
GM_deleteValue("gmail"); // Tidy up removal of gmail stuff
autoDelete(); // autodelete posts if on the deletion form
changeAccountStatus(); // change default pending status on approval screen
userLinks(); // change certain links to point to control panel user editor instead of profile.
GM_log("Finished wtf");
